﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System;

namespace NetMongo.Helper
{
    public class DateTimeConverter : DateTimeConverterBase
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
           
            DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            double time = (DateTime.Parse(value.ToString()) - startTime).TotalMilliseconds;
            writer.WriteValue(time>0?time:0);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            try
            {
                DateTime time = DateTime.MinValue;
                if(reader != null && reader.Value != null)
                {
                    DateTime.TryParse(reader.Value.ToString(), out time);
                }

                if (time > DateTime.MinValue)
                {
                    return time;
                }


                DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1, 8, 0, 0));
                long lTime = 0;
                if (reader != null && reader.Value != null)
                {
                    lTime = long.Parse(reader.Value.ToString() + "0000");
                }
                TimeSpan toNow = new TimeSpan(lTime);
                DateTime dtResult = dtStart.Add(toNow);
                return dtResult;
            }
            catch(Exception ex)
            {
                Logger.Log(ex);
                return null;
            }
            
        }
    }
}